<template>
  <el-dialog
    :model-value="visible"
    title="选择参会人"
    width="600px"
    @close="handleClose"
    destroy-on-close
  >
    <div class="user-select-container">
      <!-- 搜索框 -->
      <el-input
        v-model="searchKey"
        placeholder="搜索用户"
        clearable
        :prefix-icon="Search"
        class="mb-4"
      />

      <!-- 用户列表 -->
      <el-table
        ref="userTableRef"
        v-loading="loading"
        :data="userList"
        style="width: 100%"
        size="small"
        border
        class="mb-4"
        @selection-change="handleSelectionChange"
        row-key="uid"
      >
        <el-table-column type="selection" width="55" :reserve-selection="true" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="uid" label="用户ID" width="100" />
      </el-table>

      <!-- 分页 -->
      <div class="flex justify-center">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          layout="total,  prev, pager, next, sizes"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange" 
          :page-sizes="[10, 20, 30, 50]" 
          small
        />
      </div>
    </div>

    <!-- 底部按钮 -->
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm" :loading="confirmLoading">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch, nextTick } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import request from '@/axios/utils/request'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:visible', 'confirm'])

// 数据相关
const searchKey = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const userList = ref([])
const selectedUsers = ref([])
const loading = ref(false)
const confirmLoading = ref(false)

// 表格引用
const userTableRef = ref()

// 监听搜索关键词变化
watch(searchKey, () => {
  currentPage.value = 1
  fetchUsers()
}, { debounce: 300 })

// 获取用户列表
async function fetchUsers() {
  try {
    loading.value = true
    const response = await request.get('/user/searchUser', {
      params: {
        page: currentPage.value,
        limit: pageSize.value,
        key: searchKey.value.trim()
      }
    })

    if (response.code === 0) {
      const { list, totalCount } = response.userList
      userList.value = list
      total.value = totalCount
    } else {
      ElMessage.error(response.msg || '获取用户列表失败')
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error(error)
  } finally {
    loading.value = false
  }
}

// 处理选择变化
function handleSelectionChange(selection) {
  selectedUsers.value = selection  
}

// 处理分页大小变化
function handleSizeChange(val) {
  pageSize.value = val
  fetchUsers()
}

// 处理页码变化
function handleCurrentChange(val) {
  currentPage.value = val
  fetchUsers()
}

// 处理确认
function handleConfirm() {
  if (selectedUsers.value.length === 0) {
    ElMessage.warning('请选择用户')
    return
  }
  emit('confirm', selectedUsers.value)
}

// 处理关闭
function handleClose() {
  emit('update:visible', false)
  // 重置数据
  searchKey.value = ''
  currentPage.value = 1
  pageSize.value = 10
  userList.value = []
  selectedUsers.value = []
}

// 初始加载
fetchUsers()
</script>

<style scoped>
.user-select-container {
  min-height: 400px;
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-pagination) {
  justify-content: center;
}
</style>